package lumis.portal.channel;

import lumis.portal.PortalException;
import lumis.portal.PortalObjectAlreadyExistsException;
import lumis.portal.PortalObjectNotFoundException;
import lumis.portal.UnexpectedException;
import lumis.portal.dao.DaoException;
import lumis.portal.dao.jdbc.ITransactionJdbc;
import lumis.util.ITransaction;
import lumis.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.Stack;

/**
 * Dao implementation for channels, based on JDBC.
 * 
 * @since 4.0.0
 * @version $Revision: 13093 $ $Date: 2011-05-28 18:40:18 -0300 (Sat, 28 May 2011) $
 */
public class ChannelDaoJdbc implements IChannelDao
{
	public ChannelConfig get(String channelId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("select * from lum_Channel where channelId = ?");
			try
			{
				statement.setString(1, channelId);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					if (resultSet.next())
					{
						ChannelConfig loadedChannel = new ChannelConfig();

						loadedChannel.setId(resultSet.getString("channelId"));
						loadedChannel.setName(resultSet.getString("name"));
						loadedChannel.setDescription(resultSet.getString("description"));
						loadedChannel.setType(resultSet.getInt("type"));
						loadedChannel.setParentId(resultSet.getString("parentId"));
						loadedChannel.setHidden(resultSet.getBoolean("hidden"));
						loadedChannel.setPosition(resultSet.getInt("position"));
						loadedChannel.setTemplate(resultSet.getBoolean("isTemplate"));
						loadedChannel.setParentTemplateId(resultSet.getString("parentTemplateId"));
						loadedChannel.setPageTemplateId(resultSet.getString("pageTemplateId"));
						loadedChannel.setProtocol(resultSet.getInt("protocol"));
						loadedChannel.setInheritStylesheet(resultSet.getInt("inheritStylesheet") == 1 ? true : false);
						loadedChannel.setAccessControlListId(resultSet.getString("accessControlListId"));
						loadedChannel.setPropertyBagId(resultSet.getString("propertyBagId"));
						loadedChannel.setCenterPages(resultSet.getInt("centerPages"));
						loadedChannel.setLayoutPagesTypeInternal(resultSet.getInt("layoutPagesType"));
						loadedChannel.setLocalGroups(resultSet.getBoolean("localGroups"));
						loadedChannel.setLocalGroupPrefix(resultSet.getString("localGroupPrefix"));
						loadedChannel.setTemplateLocalGroupPrefix(resultSet.getString("templateLocalGroupPrefix"));
						loadedChannel.setCachePages(resultSet.getInt("cachePages"));
						loadedChannel.setFriendlyPathType(resultSet.getInt("friendlyPathType"));
						loadedChannel.setFriendlyPathUserDefined(resultSet.getString("friendlyPathUserDefined"));
						loadedChannel.setInheritPageTemplate(resultSet.getInt("inheritPageTemplate") == 1 ? true : false);
						loadedChannel.setInheritMetaTags(resultSet.getInt("inheritMetaTags") == 1 ? true : false);
						loadedChannel.setPageWebResourceDataProviderType(resultSet.getInt("pageWebResDataProvType"));
						loadedChannel.setPageWebResourceDataProviderClassName(resultSet.getString("pageWebResDataProv"));
						loadedChannel.setFriendlyURLPattern(resultSet.getString("friendlyURLPattern"));
						loadedChannel.setFriendlyURLPatternEnabled(resultSet.getInt("friendlyURLPatternEnabled") != 0);
						loadedChannel.setAutomaticFriendlyId(resultSet.getBoolean("automaticFriendlyId"));
						loadedChannel.setFriendlyId(resultSet.getString("friendlyId"));

						return loadedChannel;
					}
					else
						throw new PortalObjectNotFoundException("Channel id='" + channelId + "'");
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}
	}

	public void add(ChannelConfig channelConfig, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			String channelIdUsingPrefix = getIdByChannelPrefix(channelConfig, transaction);
			if (channelIdUsingPrefix != null)
				throw new ChannelPrefixInUseException(channelIdUsingPrefix, channelConfig.getLocalGroupPrefix());

			PreparedStatement statement = connection.prepareStatement("insert into lum_Channel (channelId, name, description, "
					+ "type, parentId, hidden, position, isTemplate, pageTemplateId, protocol, inheritStylesheet, accessControlListId,"
					+ "centerPages, layoutPagesType, localGroups, localGroupPrefix, templateLocalGroupPrefix, cachePages, friendlyPathType, "
					+ "friendlyPathUserDefined, parentTemplateId, inheritPageTemplate, inheritMetaTags, pageWebResDataProvType, pageWebResDataProv, "
							+ "friendlyURLPattern, friendlyURLPatternEnabled, propertyBagId, automaticFriendlyId, friendlyId) "
					+ "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
			try
			{
				statement.setString(1, channelConfig.getId());
				statement.setString(2, channelConfig.getName());
				statement.setString(3, channelConfig.getDescription());
				statement.setInt(4, channelConfig.getType());
				statement.setString(5, channelConfig.getParentId());
				statement.setInt(6, channelConfig.isHidden() ? 1 : 0);
				statement.setInt(7, channelConfig.getPosition());
				statement.setInt(8, channelConfig.isTemplate() ? 1 : 0);
				statement.setString(9, channelConfig.getPageTemplateId());
				statement.setInt(10, channelConfig.getProtocol());
				statement.setInt(11, channelConfig.isInheritStylesheet() ? 1 : 0);
				statement.setString(12, channelConfig.getAccessControlListId());
				statement.setInt(13, channelConfig.getCenterPages());
				statement.setInt(14, channelConfig.getLayoutPagesType());
				statement.setInt(15, channelConfig.hasLocalGroups() ? 1 : 0);
				statement.setString(16, channelConfig.getLocalGroupPrefix());
				statement.setString(17, channelConfig.getTemplateLocalGroupPrefix());
				statement.setInt(18, channelConfig.getCachePages());
				statement.setInt(19, channelConfig.getFriendlyPathType());
				statement.setString(20, channelConfig.getFriendlyPathUserDefined());
				statement.setString(21, channelConfig.getParentTemplateId());
				statement.setInt(22, channelConfig.isInheritPageTemplate() ? 1 : 0);
				statement.setInt(23, channelConfig.isInheritMetaTags() ? 1 : 0);
				statement.setInt(24, channelConfig.getPageWebResourceDataProviderType());
				statement.setString(25, channelConfig.getPageWebResourceDataProviderClassName());
				statement.setString(26, channelConfig.getFriendlyURLPattern());
				statement.setInt(27, channelConfig.isFriendlyURLPatternEnabled() ? 1 : 0);
				statement.setString(28, channelConfig.getPropertyBagId());
				statement.setBoolean(29, channelConfig.isAutomaticFriendlyId());
				statement.setString(30, channelConfig.getFriendlyId());
				try
				{
					statement.executeUpdate();
				}
				catch (Exception e)
				{
					try
					{
						if(get(channelConfig.getId(), transaction) != null)
							throw new PortalObjectAlreadyExistsException("STR_RESOURCE_ALREADY_EXISTS;" + channelConfig.getId(), e);
						else
							throw e;
					}
					catch (PortalObjectNotFoundException e1)
					{
						throw e;
					}
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (DaoException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public void update(ChannelConfig channelConfig, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			String channelIdUsingPrefix = getIdByChannelPrefix(channelConfig, transaction);
			if (channelIdUsingPrefix != null)
				throw new ChannelPrefixInUseException(channelIdUsingPrefix, channelConfig.getLocalGroupPrefix());

			PreparedStatement statement = connection.prepareStatement("update lum_Channel set " + "name = ?, description = ?, type = ?, parentId = ?, "
					+ "hidden = ?, position = ?, isTemplate = ?, pageTemplateId = ?, protocol = ?, inheritStylesheet = ?, "
					+ "accessControlListId = ?, centerPages = ?, layoutPagesType = ?, localGroups = ?, localGroupPrefix = ?, templateLocalGroupPrefix = ?, cachePages = ?,"
					+ "friendlyPathType = ?, friendlyPathUserDefined = ?, parentTemplateId = ?, inheritPageTemplate = ?, inheritMetaTags = ?, pageWebResDataProvType = ?, "
					+ "pageWebResDataProv = ?, friendlyURLPattern = ?, friendlyURLPatternEnabled = ?, automaticFriendlyId = ?, friendlyId = ? "
					+ " where channelId = ?");
			try
			{
				statement.setString(1, channelConfig.getName());
				statement.setString(2, channelConfig.getDescription());
				statement.setInt(3, channelConfig.getType());
				statement.setString(4, channelConfig.getParentId());
				statement.setInt(5, channelConfig.isHidden() ? 1 : 0);
				statement.setInt(6, channelConfig.getPosition());
				statement.setInt(7, channelConfig.isTemplate() ? 1 : 0);
				statement.setString(8, channelConfig.getPageTemplateId());
				statement.setInt(9, channelConfig.getProtocol());
				statement.setBoolean(10, channelConfig.isInheritStylesheet());
				statement.setString(11, channelConfig.getAccessControlListId());
				statement.setInt(12, channelConfig.getCenterPages());
				statement.setInt(13, channelConfig.getLayoutPagesType());
				statement.setInt(14, channelConfig.hasLocalGroups() ? 1 : 0);
				statement.setString(15, channelConfig.getLocalGroupPrefix());
				statement.setString(16, channelConfig.getTemplateLocalGroupPrefix());
				statement.setInt(17, channelConfig.getCachePages());
				statement.setInt(18, channelConfig.getFriendlyPathType());
				statement.setString(19, channelConfig.getFriendlyPathUserDefined());
				statement.setString(20, channelConfig.getParentTemplateId());
				statement.setBoolean(21, channelConfig.isInheritPageTemplate());
				statement.setBoolean(22, channelConfig.isInheritMetaTags());
				statement.setInt(23, channelConfig.getPageWebResourceDataProviderType());
				statement.setString(24, channelConfig.getPageWebResourceDataProviderClassName());
				statement.setString(25, channelConfig.getFriendlyURLPattern());
				statement.setInt(26, channelConfig.isFriendlyURLPatternEnabled() ? 1 : 0);
				statement.setBoolean(27, channelConfig.isAutomaticFriendlyId());
				statement.setString(28, channelConfig.getFriendlyId());
				statement.setString(29, channelConfig.getId());

				int rowsAffected = statement.executeUpdate();

				if (rowsAffected < 1)
					throw new DaoException("STR_CHANNEL_DOES_NOT_EXIST;" + channelConfig.getId());
			}
			finally
			{
				statement.close();
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public List<String> getSubChannelIds(String channelId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();
			PreparedStatement statement = null;
			try
			{
				if (channelId == null)
				{
					statement = connection.prepareStatement("select channelId from lum_Channel where parentId is null order by position asc, name asc");
				}
				else
				{
					statement = connection.prepareStatement("select channelId from lum_Channel where parentId = ? order by position asc, name asc");
					statement.setString(1, channelId);
				}

				return JdbcUtil.fillListString(statement, "channelId");
			}
			finally
			{
				if (statement != null)
					statement.close();
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public int getChannelTreeCount(String rootChannelId, ITransaction transaction) throws DaoException, PortalException
	{
		int channelCount = 0;
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			Stack<String> channelIds = new Stack<String>();
			channelIds.push(rootChannelId);
			
			PreparedStatement statement = connection.prepareStatement("select channelId from lum_Channel where parentId=?");
			try
			{
				while (!channelIds.empty())
				{
					channelCount++;
					String channelId = channelIds.pop();
					statement.setString(1, channelId);
					ResultSet resultSet = statement.executeQuery();
					try
					{
						while (resultSet.next())
							channelIds.push(resultSet.getString(1));
					}
					finally
					{
						resultSet.close();				
					}
				}
			}
			finally
			{
				if (statement != null)
					statement.close();				
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
		return channelCount;
	}

	public List<String> getChannelTreeIds(String rootChannelId, ITransaction transaction) throws DaoException, PortalException
	{
		List<String> channelIds = new ArrayList<String>();
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			channelIds.add(rootChannelId);
			
			PreparedStatement statement = connection.prepareStatement("select channelId from lum_Channel where parentId=?");
			try
			{
				int i = 0;
				while (i < channelIds.size())
				{
					String channelId = channelIds.get(i);
					statement.setString(1, channelId);
					ResultSet resultSet = statement.executeQuery();
					try
					{
						while (resultSet.next())
							channelIds.add(resultSet.getString(1));
					}
					finally
					{
						resultSet.close();				
					}
					i++;
				}
			}
			finally
			{
				if (statement != null)
					statement.close();				
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
		return channelIds;
	}
	
	public void delete(String channelId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("delete from lum_ChannelTemplateLinks where templateChannelId = ? or destinationChannelId = ?");
			try
			{
				statement.setString(1, channelId);
				statement.setString(2, channelId);
				statement.executeUpdate();
			}
			finally
			{
				statement.close();
			}

			statement = connection.prepareStatement("delete from lum_Channel where channelId = ?");
			try
			{
				statement.setString(1, channelId);
				statement.executeUpdate();
			}
			finally
			{
				statement.close();
			}
		}
		catch (DaoException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public void addCss(String channelId, String cssId, int position, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			int rowsAffected;
			PreparedStatement statement = connection.prepareStatement("UPDATE lum_ChannelCss SET position = ? WHERE channelId = ? AND cssId = ?");
			try
			{
				statement.setInt(1, position);
				statement.setString(2, channelId);
				statement.setString(3, cssId);
				rowsAffected = statement.executeUpdate();
			}
			finally
			{
				statement.close();
			}

			if (rowsAffected <= 0)
			{
				PreparedStatement stInsert = connection.prepareStatement("insert into lum_ChannelCss (channelId, cssId, position) values (?, ?, ?)");
				try
				{
					stInsert.setString(1, channelId);
					stInsert.setString(2, cssId);
					stInsert.setInt(3, position);
					
					try
					{
						stInsert.executeUpdate();
					}
					catch (Exception e)
					{
						try
						{
							Collection<String> cssIds = getCssIds(channelId, transaction);
							if (cssIds.contains(cssId))
								throw new PortalObjectAlreadyExistsException("STR_RESOURCE_ALREADY_EXISTS;" + cssId, e);
						}
						catch (PortalObjectNotFoundException e1)
						{
							throw e;
						}
					}
				}
				finally
				{
					stInsert.close();
				}
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}
	
	public void deleteCss(String channelId, String cssId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("DELETE FROM lum_ChannelCss WHERE channelId = ? AND cssId = ?");
			try
			{
				statement.setString(1, channelId);
				statement.setString(2, cssId);
				statement.executeUpdate();
			}
			finally
			{
				statement.close();
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public List<String> getCssIds(String channelId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("SELECT cssId FROM lum_ChannelCss WHERE channelId = ? ORDER BY position ASC");
			try
			{
				statement.setString(1, channelId);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					List<String> cssIds = new ArrayList<String>();

					while (resultSet.next())
						cssIds.add(resultSet.getString("cssId"));

					return cssIds;
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public boolean checkForChannelPrefix(ChannelConfig channelConfig, ITransaction transaction) throws DaoException, PortalException
	{
		return getIdByChannelPrefix(channelConfig, transaction) != null;
	}
	
	public String getIdByChannelPrefix(ChannelConfig channelConfig, ITransaction transaction) throws DaoException, PortalException
	{
		String channelUsingPrefixId = null;

		String prefix = channelConfig.getLocalGroupPrefix();
		String channelId = channelConfig.getId();

		if (prefix != null)
		{
			try
			{
				ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
				Connection connection = daoTransactionJdbc.getConnection();
				PreparedStatement statement = null;
				try
				{
					if (channelId != null)
					{
						statement = connection.prepareStatement("select channelId from lum_Channel where localGroupPrefix = ? AND channelId != ?");
						statement.setString(1, prefix);
						statement.setString(2, channelId);
					}
					else
					{
						statement = connection.prepareStatement("select channelId from lum_Channel where localGroupPrefix = ?");
						statement.setString(1, prefix);
					}

					ResultSet resultSet = statement.executeQuery();
					try
					{
						if (resultSet.next())
							channelUsingPrefixId = resultSet.getString("channelId");
					}
					finally
					{
						resultSet.close();
					}
				}
				finally
				{
					if (statement != null)
						statement.close();
				}
			}
			catch (PortalException e)
			{
				throw e;
			}
			catch (Exception e)
			{
				throw new UnexpectedException(e);
			}
		}

		return channelUsingPrefixId;
	}

	public List<String> getIdsByParentTemplateId(String parentTemplateId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("SELECT channelId FROM lum_Channel WHERE parentTemplateId = ?");
			try
			{
				statement.setString(1, parentTemplateId);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					List<String> channelIds = new ArrayList<String>();

					while (resultSet.next())
						channelIds.add(resultSet.getString("channelId"));

					return channelIds;
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}
	
	public Collection<String> getIdsByPageTemplateId(String pageTemplateId, ITransaction transaction) throws DaoException, PortalException
	{
		try
		{
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("SELECT channelId FROM lum_Channel WHERE pageTemplateId = ?");
			try
			{
				statement.setString(1, pageTemplateId);
				ResultSet resultSet = statement.executeQuery();
				try
				{
					List<String> channelIds = new ArrayList<String>();

					while (resultSet.next())
						channelIds.add(resultSet.getString("channelId"));

					return channelIds;
				}
				finally
				{
					resultSet.close();
				}
			}
			finally
			{
				statement.close();
			}
		}
		catch (PortalException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			throw new UnexpectedException(e);
		}
	}

	public String generateRandomChannelPrefix(ITransaction transaction) throws PortalException
	{
		Random rnd = new Random();
		
		while(true)
		{
			// generate a string of random 10 letters
			StringBuilder result = new StringBuilder(10);
			for (int i=0; i<10; i++)
			{
				char nextChar = (char)((rnd.nextBoolean() ? 'a' : 'A') + rnd.nextInt(26));
				result.append(nextChar);
			}
			
			// check if the result is already being used
			boolean resultInUse;
			try
			{
				Connection connection = ((ITransactionJdbc) transaction).getConnection();
				PreparedStatement statement = connection.prepareStatement("select channelId from lum_Channel where localGroupPrefix = ?");
				try
				{
					statement.setString(1, result.toString());
					ResultSet resultSet = statement.executeQuery();
					try
					{
						resultInUse = resultSet.next();
					}
					finally
					{
						resultSet.close();
					}
				}
				finally
				{
					statement.close();
				}
			}
			catch (SQLException e)
			{
				throw new UnexpectedException(e);
			}
			
			if (!resultInUse)
				return result.toString();
		}
	}

	/**
	 * Returns the number of channels using the same friendly identifier.
	 * 
	 * @param channelId
	 *            the channel identifier.
	 * @param parentId
	 *            the parent channel identifier.
	 * @param friendlyId
	 *            the friendly identifier.
	 * @param transaction
	 *            the transaction.
	 * @return the number of channels using the same friendly identifier.
	 * @since 6.0.0
	 */
	int getNumberOfChannelsUsingSameFriendlyId(String channelId, String parentId,
			String friendlyId, ITransaction transaction) throws PortalException
	{
		int ret = 0;
		try
		{
			if (channelId != null)
			{
				// channel already exists
				PreparedStatement statement = ((ITransactionJdbc) transaction)
						.getConnection()
						.prepareStatement(
								"SELECT COUNT(channelId) FROM lum_Channel WHERE parentId = ? AND NOT(channelId = ?) AND friendlyId = ?");
				try
				{
					statement.setString(1, parentId);
					statement.setString(2, channelId);
					statement.setString(3, friendlyId);
					ResultSet rs = statement.executeQuery();
					try
					{
						if (rs.next())
							ret = rs.getInt(1);
					}
					finally
					{
						rs.close();
					}
				}
				finally
				{
					statement.close();
				}
			}
			else
			{
				// channel is a new one
				PreparedStatement statement = ((ITransactionJdbc) transaction)
						.getConnection()
						.prepareStatement(
								"SELECT COUNT(channelId) FROM lum_Channel WHERE parentId = ? AND friendlyId = ?");
				try
				{
					statement.setString(1, parentId);
					statement.setString(2, friendlyId);
					ResultSet rs = statement.executeQuery();
					try
					{
						if (rs.next())
							ret = rs.getInt(1);
					}
					finally
					{
						rs.close();
					}
				}
				finally
				{
					statement.close();
				}
			}
		}
		catch (SQLException e)
		{
			throw new UnexpectedException(e);
		}

		return ret;
	}
}
